package scheduler

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"runtime"
	"sync"
	"time"
)

// Chain job 执行链
type Chain struct {
	wrapperJob []WrapperJob
}

// NewChain 创建一个执行链
func NewChain(c ...WrapperJob) *Chain {
	return &Chain{c}
}

// Then 执行链
//
//	NewChain(m1, m2, m3).Then(job)
//
// is equivalent to:
//
//	m3(m2(m1(job)))
func (c *Chain) Then(job IJob) IJob {
	for i := range c.wrapperJob {
		job = c.wrapperJob[len(c.wrapperJob)-i-1](job)
	}
	return job
}

// Recover 捕获 panic
func Recover(logger logx.Logger) WrapperJob {
	return func(job IJob) IJob {
		return FuncJob(func() {
			defer func() {
				if r := recover(); r != nil {
					const size = 64 << 10
					buf := make([]byte, size)
					buf = buf[:runtime.Stack(buf, false)]
					err, ok := r.(error)
					if !ok {
						err = fmt.Errorf("%v", r)
					}
					logger.Errorf("job panic: %v", err)
				}
				job.Run()
			}()
		})
	}
}

// DelayIfStillRunning 延迟执行
func DelayIfStillRunning(logger logx.Logger) WrapperJob {
	return func(j IJob) IJob {
		var mu sync.Mutex
		return FuncJob(func() {
			start := time.Now()
			mu.Lock()
			defer mu.Unlock()
			if dur := time.Since(start); dur > time.Minute {
				logger.Info("delay", "duration", dur)
			}
			j.Run()
		})
	}
}

// SkipIfStillRunning 跳过执行
func SkipIfStillRunning(logger logx.Logger) WrapperJob {
	return func(j IJob) IJob {
		var ch = make(chan struct{}, 1)
		ch <- struct{}{}
		return FuncJob(func() {
			select {
			case v := <-ch:
				defer func() { ch <- v }()
				j.Run()
			default:
				logger.Info("skip")
			}
		})
	}
}
